package team3.tracking.communication;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

//This class is responsible for creating gpx file,writing data to it and closing the file
public class FileManagement {	
	  private final static String outputDir = "C:\\Test\\"; //File Directory , should be change if need it!!
			public static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";    
		    public static final String TAG_GPX = "<gpx"
		            + " xmlns=\"http://www.topografix.com/GPX/1/1\""
		            + " version=\"1.1\""
		            + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
		            + " xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd \">";
		    private final static String fileName="Tracking.gpx";	 
		   public static  BufferedWriter gpsPrediction;	
//Write ClientData values to the gpx file		   
		   
	public static boolean WriteFile(ClientData cData )
	{
		  System.out.println("Writing data to the file");
		  	synchronized(gpsPrediction){
			/* Write GPS data to GPX File */
			try {
				gpsPrediction.write("\t\t\t" + "<trkpt lat=\"" + Double.toString(cData.getLatitude())+ "\" " + "lon=\"" + Double.toString(cData.getLongitude()) + "\">");
				gpsPrediction.write("<time>" +Long.toString(cData.getTimeStamp())  + "</time>");
				gpsPrediction.write("</trkpt>" + "\n");
				
				return true;
			}
			catch (IOException e)
			{
				return false;
				
			}
		}
		
	}
	//Create gpx file on given Directory path 
	public  boolean CreateFile()
	{try {
		System.out.println("Create Called");
		//File dirPrediction = new File(outputDir, "aaaaa.gpx");
		//dirPrediction.createNewFile();		
		gpsPrediction = new BufferedWriter(new FileWriter(outputDir+fileName));
		gpsPrediction.write(XML_HEADER + "\n");
		gpsPrediction.write(TAG_GPX + "\n");
		gpsPrediction.write("\t" + "<trk>" + "\n");
		gpsPrediction.write("\t\t" + "<trkseg>" + "\n");
		System.out.println("GPX File OPEN...");
		return true;
	}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
			return false;
			
		}
	}
	//Close and commit the file.
	public  boolean CloseFile()
	{
		try{
			System.out.println("Closing GPX File...");
			gpsPrediction.append("\t\t" + "</trkseg>" + "\n");
			gpsPrediction.append("\t" + "</trk>" + "\n");
			gpsPrediction.append("</gpx>"); 
			gpsPrediction.close();
			System.out.println("GPX File Closed...");
			return true;
		}
		catch(IOException error){
			return false;
		}
	}
	
	
	
}
